//
//  GWPlayMusicViewController.m
//  QQ音乐
//
//  Created by qianfeng on 16/3/9.
//  Copyright © 2016年 高炜. All rights reserved.
//

#define myColor(r,g,b) [UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:1.0]
#import "GWPlayMusicViewController.h"
#import "Masonry.h"
#import "GWPlayMusicTool.h"
#import "GWMusic.h"
#import "GWAudioTool.h"
#import "CALayer+PauseAimate.h"
#import "GWLrcView.h"
#import "GWProgressLabel.h"
@interface GWPlayMusicViewController ()<UIScrollViewDelegate,AVAudioPlayerDelegate>
@property (weak, nonatomic) IBOutlet UIImageView *bgImageView;
@property (weak, nonatomic) IBOutlet UISlider *progressView;
@property (weak, nonatomic) IBOutlet UILabel *songLabel;
@property (weak, nonatomic) IBOutlet UILabel *singerLabel;
@property (weak, nonatomic) IBOutlet UILabel *currentTimeLabel;
@property (weak, nonatomic) IBOutlet UILabel *totalTimeLabel;
@property (weak, nonatomic) IBOutlet UIImageView *iconImage;
@property (weak, nonatomic) IBOutlet GWProgressLabel *lrcLabel;


@property (weak, nonatomic) IBOutlet UIButton *starOrPause;

- (IBAction)starTouch:(id)sender;
- (IBAction)endTouch:(id)sender;
- (IBAction)valueChange:(id)sender;
- (IBAction)touchProgress:(id)sender;

- (IBAction)previousMusic;
- (IBAction)starOrPuasw;
- (IBAction)nextMusic;

@property (weak, nonatomic) IBOutlet GWLrcView *lrcView;


@property (nonatomic,strong)NSTimer *progressTimer;
@property (nonatomic,weak)AVAudioPlayer *currentPlayer;
@property (nonatomic,strong)CADisplayLink* lrcTimer;

@end

@implementation GWPlayMusicViewController
-(void)viewWillLayoutSubviews
{
    [super viewWillLayoutSubviews];
    self.iconImage.layer.cornerRadius =self.iconImage.frame.size.width*0.5;
    self.iconImage.layer.masksToBounds =YES;
    self.iconImage.layer.borderWidth =8;
    self.iconImage.layer.borderColor =myColor(36, 36, 36).CGColor;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUpblurView];
  
    [self.progressView setThumbImage:[UIImage imageNamed:@"player_slider_playback_thumb"] forState:UIControlStateNormal];
    [self playCurrentMusic];
    self.lrcView.delegate =self;
    
    
}
-(void)setUpblurView
{
    UITabBar *tabbar =[[UITabBar alloc]init];
    [tabbar setBarStyle:UIBarStyleBlack];
    [self.bgImageView addSubview:tabbar];
    tabbar.translatesAutoresizingMaskIntoConstraints =NO;
    [tabbar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.bgImageView.mas_top);
        make.left.equalTo(self.bgImageView.mas_left);
        make.bottom.equalTo(self.bgImageView.mas_bottom);
        make.right.equalTo(self.bgImageView.mas_right);
    }];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}
-(void)playCurrentMusic
{
    
   GWMusic *music = [GWPlayMusicTool currentPlayingMusic];
    self.songLabel.text =music.name;
    self.singerLabel.text =music.singer;
    
    self.bgImageView.image =[UIImage imageNamed:music.icon];
    self.iconImage.image =[UIImage imageNamed:music.icon];
  AVAudioPlayer *player = [GWAudioTool playMusicWithMusicName:music.filename];
    player.delegate =self;
    self.currentTimeLabel.text =[self timeStrWithDoubleTime:player.currentTime];
    self.totalTimeLabel.text =[self timeStrWithDoubleTime:player.duration];
    self.currentPlayer =player;
    self.starOrPause.selected =player.isPlaying;
    
    [self startIconViewAnminition];
    //添加之前先移除
    [self removeProgressTimer];
    [self addProgressTimer];
    
    [self removeLrcTimer];
    [self addLrcTimer];
    self.lrcView.lrcName =music.lrcname;
    self.lrcView.homeLrcLable =self.lrcLabel;
    self.lrcView.currentPlayer =player;
//    [self setLockScreenInfo];
}
-(void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
    if (flag) {
        [self nextMusic];
    }
}
-(void)addProgressTimer
{
    [self upDateProgressInfo];
   self.progressTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(upDateProgressInfo) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop]addTimer:self.progressTimer forMode:NSRunLoopCommonModes];
}

-(void)removeProgressTimer
{
    [self.progressTimer invalidate];
    self.progressTimer =nil;
}
-(void)upDateProgressInfo
{
    self.currentTimeLabel.text =[self timeStrWithDoubleTime:self.currentPlayer.currentTime];
    self.progressView.value =self.currentPlayer.currentTime/self.currentPlayer.duration;

}
-(void)addLrcTimer
{
    self.lrcTimer =[CADisplayLink displayLinkWithTarget:self selector:@selector(upDateLrcTime)];
    [self.lrcTimer addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
}

-(void)removeLrcTimer
{
    [self.lrcTimer invalidate];
    self.lrcTimer =nil;
}
-(void)upDateLrcTime
{
    self.lrcView.currentTime =self.currentPlayer.currentTime;
}

-(void)startIconViewAnminition
{
    CABasicAnimation *animation =[CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    animation.fromValue =@(0);
    animation.toValue =@(M_PI*2);
    animation.repeatCount =NSIntegerMax;
    animation.duration =40;
    [self.iconImage.layer addAnimation:animation forKey:nil];
}
-(NSString *)timeStrWithDoubleTime:(NSTimeInterval )time
{
    NSInteger min =time/60;
    NSInteger sen =(NSInteger)time %60;
    return [NSString stringWithFormat:@"%02ld:%02ld",min,sen];
}

- (IBAction)starTouch:(id)sender {
    [self removeProgressTimer];
}

- (IBAction)endTouch:(id)sender {
    self.currentPlayer.currentTime =self.currentPlayer.duration *self.progressView.value;
    
    [self addProgressTimer];
}

- (IBAction)valueChange:(id)sender {
    self.currentTimeLabel.text =[self timeStrWithDoubleTime:self.currentPlayer.duration *self.progressView.value];
}

- (IBAction)touchProgress:(UITapGestureRecognizer *)sender {
   CGPoint point = [sender locationInView:sender.view];
    CGFloat value = point.x /self.progressView.frame.size.width;
    self.currentPlayer.currentTime =self.currentPlayer.duration *value;
    
    [self upDateProgressInfo];
}

- (IBAction)previousMusic {
    GWMusic *currentMusic =[GWPlayMusicTool currentPlayingMusic];
    [GWAudioTool stopMusicWithMusicName:currentMusic.filename];
    GWMusic *previousMusic =[GWPlayMusicTool previousMusic];
    
    [GWPlayMusicTool setCurrentMusicWithMusic:previousMusic];
    
    [self playCurrentMusic];
}

- (IBAction)starOrPuasw {
    GWMusic *music =[GWPlayMusicTool currentPlayingMusic];
    if (self.currentPlayer.isPlaying) {
        [GWAudioTool pauseMusicWithMusicName:music.filename];
        [self.iconImage.layer pauseAnimate];
    }
    else
    {
        [GWAudioTool playMusicWithMusicName:music.filename];
        [self.iconImage.layer resumeAnimate];
    }
    
    self.starOrPause.selected =self.currentPlayer.isPlaying;
}

- (IBAction)nextMusic {
    
    GWMusic *currentMusic =[GWPlayMusicTool currentPlayingMusic];
    [GWAudioTool stopMusicWithMusicName:currentMusic.filename];
    GWMusic *nextMusic =[GWPlayMusicTool nextMusic];
    
    [GWPlayMusicTool setCurrentMusicWithMusic:nextMusic];
    
    [self playCurrentMusic];
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat scale =scrollView.contentOffset.x/scrollView.frame.size.width;
    self.iconImage.alpha =1-scale;
    self.lrcLabel.alpha =1-scale;
}



-(void)remoteControlReceivedWithEvent:(UIEvent *)event
{
    switch (event.subtype) {
        case UIEventSubtypeRemoteControlPlay:
        case UIEventSubtypeRemoteControlPause:
            [self starOrPuasw];
            break;
        case UIEventSubtypeRemoteControlNextTrack:
            [self nextMusic];
            break;
        case UIEventSubtypeRemoteControlPreviousTrack:
            [self previousMusic];
            break;
        default:
            break;
    }
}
@end
